<template>
  <n-card>
    <n-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <n-form-item label="标题" prop="title">
        <n-input
          v-model:value="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </n-form-item>
      <n-form-item label="模型" prop="model">
        <n-select v-model:value="queryParams.model" placeholder="请选择模型" clearable>
          <n-option
            v-for="dict in dict.type.sys_process_category"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </n-select>
      </n-form-item>
      <n-form-item label="创建时间" prop="createTime">
        <n-date-picker clearable
                      v-model:value="queryParams.createTime"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="请选择创建时间">
        </n-date-picker>
      </n-form-item>
      <n-form-item>
        <n-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</n-button>
        <n-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</n-button>
      </n-form-item>
    </n-form>

    <n-space :gutter="10" class="mb8">
      <n-button
        type="primary"
        plain
        icon="el-icon-plus"
        size="mini"
        @click="handleAdd"
      >新增
      </n-button>
      <n-button
        type="success"
        plain
        icon="el-icon-edit"
        size="mini"
        :disabled="single"
        @click="handleUpdate"
      >修改
      </n-button>
      <n-button
        type="danger"
        plain
        icon="el-icon-delete"
        size="mini"
        :disabled="multiple"
        @click="handleDelete"
      >删除
      </n-button>
      <n-button
        type="warning"
        plain
        icon="el-icon-download"
        size="mini"
        @click="openPublishDialog"
      >发布
      </n-button>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </n-space>

    <n-data-table
      :loading="loading"
      :data="noteList"
      @update:checked-row-keys="handleSelectionChange"
      :columns="columns"
    />

    <n-pagination
      v-show="total>0"
      :page="queryParams.pageNum"
      :page-size="queryParams.pageSize"
      :item-count="total"
      @update:page="queryParams.pageNum = $event"
      @update:page-size="queryParams.pageSize = $event"
    />

    <n-modal v-model:show="publishDialogVisible" title="选择用户" width="600px">
      <n-data-table
        :data="userList"
        @update:checked-row-keys="handleuserSelectionChange"
        :columns="userColumns"
      />
      <template #action>
        <n-space>
          <n-button @click="publishDialogVisible = false">取消</n-button>
          <n-button type="primary" @click="submitPublish">确定</n-button>
        </n-space>
      </template>
    </n-modal>

    <n-modal v-model:show="open" :title="title" width="1000px" :z-index="3000">
      <n-space vertical>
        <n-space>
          <n-text>内容创作数字员工</n-text>
          <n-select v-model:value="form.employeeId" placeholder="请选择">
            <n-option
              v-for="item in employees"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </n-select>
          <n-text>网页设计数字员工</n-text>
          <n-select v-model:value="form.designerId" placeholder="请选择">
            <n-option
              v-for="item in filteredEmployees"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </n-select>
          <n-button type="primary" @click="generateContent" :loading="loading">生成</n-button>
        </n-space>

        <n-input
          type="textarea"
          :rows="3"
          placeholder="请输入需要生成文章的提示词"
          v-model:value="prompt"
        />

        <n-card>
          <n-h4>生成的文案</n-h4>
          <v-md-editor v-model="generatedText" height="500px"></v-md-editor>
        </n-card>
      </n-space>
      <template #action>
        <n-space>
          <n-button type="primary" @click="submitForm">确 定</n-button>
          <n-button @click="cancel">取 消</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>

<script>
import { ref, computed } from 'vue';
import {
  NButton,
  NCard,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NDatePicker,
  NSpace,
  NDataTable,
  NPagination,
  NModal,
  NH4,
  NText
} from 'naive-ui';
import {listNotes, delNote, updateNote, generateImage, getNote} from "@/api/note";
import {chat, saveContentToServer} from '@/api/chats';
import {listEmployee} from "@/api/employee";
import {listAccount, listSearch, reNotes} from "@/api/account";

export default {
  components: {
    NButton,
    NCard,
    NForm,
    NFormItem,
    NInput,
    NSelect,
    NDatePicker,
    NSpace,
    NDataTable,
    NPagination,
    NModal,
    NH4,
    NText
  },
  setup() {
    const queryParams = ref({
      pageNum: 1,
      pageSize: 10,
      content: null,
      title: null,
      prompt: null,
      model: null,
      createTime: null,
    });
    const form = ref({});
    const noteList = ref([]);
    const userList = ref([]);
    const selectedUsers = ref([]);
    const employees = ref([
      {value: '1', label: '员工1'},
      {value: '2', label: '员工2'},
    ]);
    const prompt = ref('小户型装修避坑指南');
    const generatedText = ref('');
    const loading = ref(true);
    const ids = ref([]);
    const single = ref(true);
    const multiple = ref(true);
    const showSearch = ref(true);
    const total = ref(0);
    const title = ref("");
    const open = ref(false);
    const publishDialogVisible = ref(false);
    const selectedEmployee = ref('');
    const designerEmployee = ref('');

    const columns = [
      { type: 'selection', width: 55, align: 'center' },
      { title: '主键', key: 'id', align: 'center' },
      { title: '标题', key: 'title', width: 260, align: 'center' },
      { title: '内容', key: 'content', width: 260, align: 'center' },
      { title: '内容创作数字员工', key: 'employeeId', align: 'center' },
      { title: '网页设计数字员工', key: 'designerId', align: 'center' },
      { title: '图片', key: 'contentImg', width: 120, align: 'center' },
      { title: '创建时间', key: 'createTime', width: 120, align: 'center' },
      { title: '操作', key: 'actions', width: 220, align: 'center' }
    ];

    const userColumns = [
      { type: 'selection', width: 55 },
      { title: '账号', key: 'account' },
      { title: 'ID', key: 'id' }
    ];

    const filteredEmployees = computed(() => {
      return employees.value.filter(item =>
        item.value !== selectedEmployee.value &&
        item.value !== designerEmployee.value
      );
    });

    const getList = () => {

      loading.value = true;
      listNotes(queryParams.value).then(response => {
				console.log('11111111111111111111111111111');
				console.log('11111111111111111111111111111',response);
        noteList.value = response.data.list;
        total.value = response.data.total;
        loading.value = false;
      });
    };

    const handleQuery = () => {
      queryParams.value.pageNum = 1;
      getList();
    };

    const resetQuery = () => {
      queryParams.value = {
        pageNum: 1,
        pageSize: 10,
        content: null,
        title: null,
        prompt: null,
        model: null,
        createTime: null,
      };
      handleQuery();
    };

    const handleSelectionChange = (selection) => {
      ids.value = selection;
      single.value = selection.length !== 1;
      multiple.value = !selection.length;
    };

    const handleAdd = () => {
      form.value = {};
      open.value = true;
      title.value = "添加文章内容";
    };

    const handleUpdate = (row) => {
      form.value = {};
      const id = row.id || ids.value[0];
      getNote(id).then(response => {
        form.value = response.data;
        generatedText.value = response.data.content;
        open.value = true;
        title.value = "修改文章内容";
      });
    };

    const submitForm = () => {
      form.value.content = generatedText.value;
      if (form.value.id != null) {
        updateNote(form.value).then(response => {
          open.value = false;
          getList();
        });
      } else {
        saveContentToServer(form.value).then(response => {
          open.value = false;
          getList();
        });
      }
    };

    const handleDelete = (row) => {
      const id = row.id || ids.value[0];
      delNote(id).then(() => {
        getList();
      });
    };

    const listEmployees = () => {
      listEmployee({
        pageNum: 1,
        pageSize: 100
      }).then(response => {
        employees.value = response.rows.map(item => ({
          value: item.id,
          label: item.name
        }));
      });
    };

    const generateContent = () => {
      generatedText.value = '';
      loading.value = true;
      const data = {
        employeeId: selectedEmployee.value,
        prompt: prompt.value
      };
      /*sseRequest.create({
        url: '/ai/content/stream',
        method: 'POST',
        body: data,
        onMessage: (response) => {
          const result = response.result;
          if (result) {
            const output = result.output;
            if (output.text) {
              generatedText.value += output.text;
            }
          }
        },
        onError: (err) => {
          console.error('SSE 错误:', err);
          chatContent(data);
        },
        onClose: () => {
          console.log('SSE 关闭');
          loading.value = false;
        }
      });*/
    };

    const chatContent = (data) => {
      chat(data).then((response) => {
        if (response.code === 200) {
          const result = response.data.result;
          const text = result.output.text;
          if (text) {
            generatedText.value += text;
          }
        }
      }).finally(() => {
        loading.value = false;
      });
    };

    const openPublishDialog = () => {
      if (ids.value.length === 0) {
        alert("请勾选需要发布的文章");
      } else {
        publishDialogVisible.value = true;
        fetchUserList();
      }
    };

    const fetchUserList = () => {
      listAccount({
        "loginStatus": 1
      }).then(response => {
        userList.value = response.rows;
      });
    };

    const handleuserSelectionChange = (selection) => {
      selectedUsers.value = selection;
    };

    const submitPublish = () => {
      if (selectedUsers.value.length === 0) {
        alert("请勾选需要发布的用户");
      } else {
        reNotes({
          "accountIds": selectedUsers.value,
          "noteIds": ids.value
        }).then(response => {
        });
        publishDialogVisible.value = false;
      }
    };

    return {
      queryParams,
      form,
      noteList,
      userList,
      selectedUsers,
      employees,
      prompt,
      generatedText,
      loading,
      ids,
      single,
      multiple,
      showSearch,
      total,
      title,
      open,
      publishDialogVisible,
      selectedEmployee,
      designerEmployee,
      columns,
      userColumns,
      filteredEmployees,
      getList,
      handleQuery,
      resetQuery,
      handleSelectionChange,
      handleAdd,
      handleUpdate,
      submitForm,
      handleDelete,
      listEmployees,
      generateContent,
      chatContent,
      openPublishDialog,
      fetchUserList,
      handleuserSelectionChange,
      submitPublish
    };
  }
};
</script>

<style scoped>
.n-select {
  position: relative !important;
  z-index: 3000 !important;
}
</style>
